package com.example.zk2_lx;

import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;

import com.alibaba.android.arouter.launcher.ARouter;
import com.example.zk2_lx.db.AppDBUtils;
import com.hyphenate.EMMessageListener;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMMessage;
import com.hyphenate.chat.EMOptions;
import com.hyphenate.chat.EMTextMessageBody;
import com.hyphenate.easeui.EaseIM;

import java.util.List;

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        EMOptions options = new EMOptions();
        options.setAppKey("1104230426171869#2203im");
        EMClient.getInstance().init(this, options);

        ARouter.openDebug();
        ARouter.openLog();
        ARouter.init(this);

        //EaseIM 初始化
        if(EaseIM.getInstance().init(this, options)){
            //在做打包混淆时，关闭 debug 模式，避免消耗不必要的资源
            EMClient.getInstance().setDebugMode(true);
            //EaseIM 初始化成功之后再调用注册消息监听的代码 ...
        }
        AppDBUtils.getInstance().init(this);

        EMClient.getInstance().chatManager().addMessageListener(new EMMessageListener() {
            @Override
            public void onMessageReceived(List<EMMessage> messages) {
                for (EMMessage message : messages) {
                    String str = "";
                   if(message.getType()== EMMessage.Type.TXT){
                       str = ((EMTextMessageBody)(message.getBody())).getMessage();
                   }else{
                       str="非文本消息";
                   }
                    Intent intent = new Intent(getApplicationContext(),ChatActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("conversationId",message.conversationId());
                    bundle.putInt("chatType",0);
                    intent.putExtra("bundle",bundle);
                    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),102,intent,PendingIntent.FLAG_UPDATE_CURRENT);
                    //发送通知
                    Notification notification = new Notification.Builder(getApplicationContext())
                            .setSmallIcon(R.mipmap.ic_launcher)
                            .setContentTitle("接收到新消息")
                            .setContentText(str)
                            .setAutoCancel(true)
                            .setContentIntent(pendingIntent)
                            .build();
                    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    manager.notify(1,notification);
                }
            }
        });
    }
}
